package study.source.eunsung.controller;


import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.read.biff.BiffException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import study.source.common.util.ExcelReaderJxl;
import study.source.common.util.ExcelReaderPoi;
import study.source.common.util.FileUtil;

@Controller
@RequestMapping("/excel")
public class ExcelReadController {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@RequestMapping( value = "/main", method = RequestMethod.GET)
	public String excelMainPage(ModelMap modelMap,
			HttpServletRequest request, HttpServletResponse response){
		
		return "eunsung/excel/main";
	}
	
	@RequestMapping( value = "/get/data")
	public String excelGetData(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) 
			throws BiffException, IOException{
		
		MultipartRequest multipartRequest = (MultipartRequest)request;
		MultipartFile excelFileUp = multipartRequest.getFile("excelFile");
		
		FileUtil fileUtil = new FileUtil();
		
		String filePath = fileUtil.fileUpload(request, excelFileUp);
		
		List<String[]> data = null;
		
		File excelFile = new File(filePath);
		String type = filePath.substring(filePath.lastIndexOf(".")+1);
		
		if(type.equals("xls")){
			ExcelReaderJxl excelReaderJxl = new ExcelReaderJxl(excelFile);
			data = excelReaderJxl.excelRead();
		}else if(type.equals("xlsx")){
			ExcelReaderPoi excelReaderPoi = new ExcelReaderPoi(excelFile);
			data = excelReaderPoi.excelRead();
		}
		
		excelFile.delete();
		
		for(int i=0;i<data.size();i++){
			for(int j=0;j<data.get(i).length;j++){
				System.out.print(data.get(i)[j]+"\t");
			}
			System.out.println();
		}
		
		modelMap.addAttribute("value", data);
		
		return ":json";
	}
	
}
